package cn.wolfcode.p2p.website.web.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.base.util.LoginInfoContext;

/**
 *
 */
@Controller
public class LoginInfoController {
	@Autowired
	private ILoginInfoService loginInfoService;
	

	@RequestMapping("/register")
	@ResponseBody
	public Object register( @Valid LoginInfo loginInfo, String verifyCode){ // 后端校验的注解
		JSONResult result = new JSONResult();
		try {
			loginInfoService.register(loginInfo.getUsername(), loginInfo.getPassword(), verifyCode);
		} catch (Exception e) {
			e.printStackTrace();
			result.mark(e.getMessage());
		}
		return result;
	}
	//查重
	@RequestMapping("/checkUsernameExist")
	@ResponseBody
	public boolean checkUsernameExist(String username){
		boolean boo = loginInfoService.getUsernameExist(username);
		return !boo;
	}

	// 登录
	@PostMapping("/login")
	@ResponseBody
	public Object login(String username, String password){
		JSONResult result = new JSONResult();
		// 前台登录只能登录前台用户
		LoginInfo loginInfo = loginInfoService.login(username, password, LoginInfo.TYPE_USER);
		if (loginInfo == null) {
			result.mark("账号或密码错误");
		}
		return result;
	}
	// 注销
	@RequestMapping("/logout")
	public Object logout(){
        // 清空session的验证码vo对象
        LoginInfoContext.setCurrentLoginInfo(null);
		return "redirect:/login.html";
	}

	



}
